<?php
/**
 * Created by PhpStorm.
 * User: Tioncico
 * Date: 2019/3/18 0018
 * Time: 10:45
 */

namespace App\HttpController;


use EasySwoole\EasySwoole\Logger;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Message\Status;
use EasySwoole\EasySwoole\Trigger;

abstract class Base extends ViewController
{
    /**
     * 未定义index跳转到某认首页
     */
    function index()
    { 
        $this->actionNotFound('index');
    }

    protected function onRequest(?string $action): ?bool
    {

        $this->action_method=$action;
        //模拟拦截
        //当没有传code的时候则拦截
//        if (empty($this->request()->getRequestParam('code'))) {
//            $this->writeJson(Status::CODE_BAD_REQUEST, ['errorCode' => 1, 'data' => []], 'code不存在');
//            return false;
//        }
        return true;
    }

    /**
     * 异常处理
     * @param \Throwable $throwable
     */
    protected function onException(\Throwable $throwable): void
    {
        $this->writeJson($throwable->getMessage(), null, $throwable->getCode());
    }

    /**
     * URL重定向
     * @param string $url 重定向的URL地址
     * @param integer $time 重定向的等待时间（秒）
     * @param string $msg 重定向前的提示信息
     * @return void
     */
    function redirect($url, $time=0, $msg='') {
        //多行URL地址支持
        $url        = str_replace(array("\n", "\r"), '', $url);
        if (empty($msg))
            $msg    = "系统将在{$time}秒之后自动跳转到{$url}！";
        if (!headers_sent()) {
            // redirect
            if (0 === $time) {
                header('Location: ' . $url);
            } else {
                header("refresh:{$time};url={$url}");
                $this->response()->write($msg);
            }

        } else {
            $str    = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
            if ($time != 0)
                $str .= $msg;
             $this->response()->write($str) ;
        }
    }



    /**
     * 数据返回格式
     * @param int $statusCode
     * @param null $result
     * @param null $msg
     * @return bool
     */
    protected function writeJson($msg = null, $result = null, $statusCode = 200, $headerStatus = 200)
    {
        if (!$this->response()->isEndResponse()) {
            $data = Array(
                'code' => 0,
                'status' => $statusCode,
                'data' => $result,
                'message' => $msg
            );
            $this->response()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
            $this->response()->withStatus($headerStatus);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 有分页的返回格式
     * @param null $msg
     * @param null $result
     * @param int $statusCode
     * @param int $headerStatus
     * @return bool
     */
    protected function writePageJson($msg = null, $result = null, $statusCode = 200, $headerStatus = 200)
    {
        if (!$this->response()->isEndResponse()) {
            $data = Array(
                'code' => 0,
                'status' => $statusCode,
                'count'=>$result['total'],
                'data' => $result['list'],
                'message' => $msg
            );
            $this->response()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
            $this->response()->withStatus($headerStatus);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断是否是POST请求
     * @return bool
     */
    public function isPost()
    {
        if ($this->request()->getMethod() == 'POST') {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取GET参数
     * @param $key
     * @return array|mixed
     */
    public function getParam($key, $default = null)
    {
        $data = $this->request()->getQueryParams();
        if (isset($data[$key])) {
            return $this->paramsFilter($data[$key]);
        } else {
            return $default;
        }
    }

    /**
     * 获取所有GET参数
     * @return array|mixed
     */
    public function getParams()
    {
        $data = $this->request()->getQueryParams();
        foreach ($data as $key => $value) {
            $data[$key] = $this->paramsFilter($value);
        }
        return $data;
    }

    /**
     * 获取POST参数
     * @param $key
     * @return array|mixed
     */
    public function postParam($key, $default = null)
    {
        $data = $this->request()->getParsedBody();
        if (isset($data[$key])) {
            return $this->paramsFilter($data[$key]);
        }
        return $default;
    }

    /**
     * 获取所有POST参数
     * @return array|mixed
     */
    public function postParams()
    {
        $data = $this->request()->getParsedBody();
        foreach ($data as $key => $value) {
            $data[$key] = $this->paramsFilter($value);
        }
        return $data;
    }

    /**
     * 获取GET&POST参数
     * @param $key
     * @return array|mixed
     */
    public function requestParam($key, $default = null)
    {
        return $this->postParam($key) ?: ($this->getParam($key) ?: $default);
    }

    /**
     * 获取所有参数
     * @return array|mixed
     */
    public function requestParams()
    {
        return array_merge($this->getParams(), $this->postParams());
    }

    /**
     * 数组过滤
     * @param $data
     * @return array|null|string
     */
    public  function paramsFilter($data)
    {
        if (is_array($data)) {
            return $this->arrayRecursion($data, function ($v) {
                return trim($v);
            });
        } elseif (is_string($data)) {
            return trim($data);
        } else {
            return null;
        }
    }

    /**
     * 数组去空格
     * @param $arrayData
     * @return array
     */
    public  function arrayRecursion($arrayData, callable $fun)
    {
        return array_map(function ($v) use ($fun) {
            if (is_array($v)) {
                return $this->arrayRecursion($v, $fun);
            }
            return call_user_func($fun, $v);
        }, $arrayData);
    }

}